package logic

import (
	"context"
	"fmt"
	"vipshop/model/mysql"
	"vipshop/model/redisinit"
	"vipshop/pkg"

	"vipshop/vipshoprpc/internal/svc"
	"vipshop/vipshoprpc/vipshoprpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLogInLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLogInLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLogInLogic {
	return &UserLogInLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLogInLogic) UserLogIn(in *vipshoprpc.UserLogInRequest) (*vipshoprpc.UserLogInResponse, error) {
	// todo: add your logic here and delete this line
	capGet := redisinit.Rdb.Get("captchaLogIn" + in.Phone)
	if capGet.Val() != in.CaptchaCode {
		return nil, fmt.Errorf("图形验证码错误")
	}
	sendGet := redisinit.Rdb.Get("sendSmsLogIn" + in.Phone)
	if sendGet.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("短信验证码错误")
	}
	var user mysql.User
	mysql.DB.Debug().Where("phone = ?", in.Phone).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该用户不存在,请前往注册")
	}
	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码错误")
	}
	redisinit.Rdb.Del("captchaLogIn" + in.Phone)
	redisinit.Rdb.Del("sendSmsLogIn" + in.Phone)
	return &vipshoprpc.UserLogInResponse{
		Id: int64(user.ID),
	}, nil
}
